package my.mall.admin.api.service

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import my.mall.admin.api.enums.AdminStatusEnum
import my.mall.admin.api.pojo.login.LoginParam
import my.mall.common.enums.RespMetaEnum
import my.mall.common.exception.WebBaseException
import my.mall.common.util.JwtUtils
import my.mall.common.util.PasswordUtils
import my.mall.db.entity.Admin
import my.mall.db.mapper.AdminMapper
import org.springframework.stereotype.Service
import java.time.LocalDate
import java.util.*

@Service
open class LoginService(
    private val adminMapper: AdminMapper
) {

    open fun login(loginParam: LoginParam): Map<String, String> {
        val admin = adminMapper.selectOne(
            QueryWrapper<Admin>()
                .select(Admin.ID, Admin.PASSWORD, Admin.ADMIN_STATUS, Admin.FAILED_DATE, Admin.FAILED_NUM)
                .eq(Admin.PHONE_NUM, loginParam.phoneNum)
        )
        if (admin == null || AdminStatusEnum.DISABLE.status == admin.adminStatus) {
            throw WebBaseException(RespMetaEnum.NO_USER)
        }
        if (LocalDate.now() == admin.failedDate && admin.failedNum!! >= 3) {
            throw WebBaseException(RespMetaEnum.REPEAT_PWD_ERROR)
        }
        val password = PasswordUtils.md5(loginParam.password)
        if (admin.password != password) {
            var num: Byte = 0
            if (LocalDate.now() == admin.failedDate) {
                num = admin.failedNum!!
            }
            adminMapper.updateLoginFailedNum(LocalDate.now(), num + 1, admin.id!!)
            throw WebBaseException(RespMetaEnum.PWD_ERROR)
        }
        adminMapper.updateLoginFailedNum(LocalDate.now(), 0, admin.id!!)
        val token = JwtUtils.createToken(admin.id)
        return Collections.singletonMap("token", token)
    }
}